//
//  CacheProjectsUtil.m
//  song-git
//
//  Created by song on 16/2/23.
//  Copyright © 2016年 song. All rights reserved.
//

#import "CacheProjectsUtil.h"


static NSString * const insertUser = @"INSERT OR IGNORE INTO User(user_id,name,portrait_url)VALUES(?,?,?)";

static NSString * const insertProject =@"INSERT OR IGNORE INTO Project(id,userId,name,description,path_with_namespace,language,forks_count,stars_count,watches_count,recomm,projectsType) VALUES(?,?,?,?,?,?,?,?,?,?,?)";

static NSString * const insertLanguage =@"INSERT OR IGNORE INTO Language(id,name) VALUES(?,?)";


@interface CacheProjectsUtil()

@property(nonatomic ,strong) FMDatabase *dataBase;
@property(nonatomic, copy) NSString *path;

@end

@implementation CacheProjectsUtil


+(instancetype)shareInstance
{
    static CacheProjectsUtil *cache;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        cache = [CacheProjectsUtil new];
        NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        docsDirectory = [docsDirectory stringByAppendingPathComponent:@"GitProject.sqlite"];
        cache.path = docsDirectory;
        NSLog(@"cache.path :%@",cache.path);
        cache.dataBase = [FMDatabase databaseWithPath:cache.path];
        
        [cache createUser];
        [cache createProjects];
        [cache createLanguages];
    });
    
    return cache;
}

-(void)createUser
{
    if([_dataBase open])
    {
        NSString *sql=@"CREATE TABLE IF NOT EXISTS User"
                      @"( "
                      @"user_id INTEGER PRIMARY KEY NOT NULL,"
                      @"name TEXT,"
                      @"portrait_url TEXT"
                      @"); ";
        
        [_dataBase executeUpdate:sql];
        [_dataBase close];
    }
    
    
}
-(void)createProjects
{
    if([_dataBase open])
    {
        NSString *sql = @"CREATE TABLE IF NOT EXISTS Project"
                        @"("
                        @"id INTEGER PRIMARY KEY NOT NULL ,"
                        @"userID INTEGER,"
                        @"name TEXT,"
                        @"description TEXT,"
                        @"path_with_namespace TEXT,"
                        @"language TEXT,"
                        @"forks_count INTEGER,"
                        @"stars_count INTEGER,"
                        @"watches_count INTEGER,"
                        @"recomm BOOL,"
                        @"projectsType INTEGER"
                        @");";
        [_dataBase executeUpdate:sql];
        [_dataBase close];
    }
}

-(void)createLanguages
{
    if([_dataBase open])
    {
            NSString *sql = @"CREATE TABLE IF NOT EXISTS Language"
                            @"("
                            @"id INTEGER PRIMARY KEY NOT NULL,"
                            @"name TEXT"
                            @");";
        [_dataBase executeUpdate:sql];
        [_dataBase close];
    }
    
}

-(void)insertProjectList:(NSArray *)projects andProjectType:(ProjectsType)projectsType
{
    if([_dataBase open])
    {
        for(GLProject *project in projects)
        {
            [self p_insertProject:project andProjectType:projectsType];
        }
        [_dataBase close];
    }
}

-(void)p_insertProject:(GLProject *)project andProjectType:(ProjectsType)projectsType
{
    [_dataBase executeUpdate:insertProject,
        @(project.projectId),
        @(project.owner.userId),
        project.name,
        project.projectDescription,
        project.nameSpace,
        project.language,
        @(project.forksCount),
        @(project.starsCount),
        @(project.watchesCount),
        @(project.recomm),
        @(projectsType)];
    
    [_dataBase executeUpdate:insertUser,
        @(project.owner.userId),
        project.owner.portrait
     ];
    
}
-(NSArray *)readProjectListWithProjectType:(ProjectsType)projectType
{
    NSMutableArray *projects = [NSMutableArray new];
    
    if([_dataBase open])
    {
        NSString *sql =[NSString stringWithFormat:@"select * from Project where projectsType=%lu",(unsigned long)projectType ];
        FMResultSet *result =[_dataBase executeQuery:sql];
        while ([result next]) {
            GLProject *project = [GLProject new];
            project.projectId  =[result intForColumn:@"id"];
            project.name = [result stringForColumn:@"name"];
            project.projectDescription = [result stringForColumn:@"description"];
            project.nameWithNamespace = [result stringForColumn:@"path_with_namespace"];
            project.language = [result stringForColumn:@"language"];
            project.forksCount =[result  intForColumn:@"forks_count"];
            project.starsCount = [result intForColumn:@"stars_count"];
            project.watchesCount = [result intForColumn:@"watches_count"];
            project.recomm = [result boolForColumn:@"recomm"];
            NSInteger userid = [result intForColumn:@"userId"];
            project.owner  =[self readUser:userid];
            [projects addObject:project];
        }
        
    }
    
    return projects;
}

-(GLUser *)readUser:(NSInteger)userID
{
    NSString *sql =[NSString stringWithFormat:@"select * from user where user_id =%ld;",userID];
    FMResultSet *result = [_dataBase executeQuery:sql];
    GLUser *user = [GLUser new];
    
    if([result next])
    {
        user.userId = [result intForColumn:@"user_id"];
        user.name = [result stringForColumn:@"name"];
        user.portrait = [result stringForColumn:@"portrait_url"];
    }
    return user;
}

@end
